#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include <assert.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <iostream>

#include <rpm/rpmlib.h>

#include "rapt-compat.h"
#include "crpmtag.h"
#include "genutil.h"

int main(int c, char **v) {
    if (c != 3)
	return 1;

    char *rpms_path = v[1];
    char *stripped_path = v[2];
    int entry_no, entry_cur;
    struct dirent **dirEntries;

    int stripdir = open(stripped_path, O_DIRECTORY);
    if (stripdir < 0) {
       std::cerr << "create-header-copy: open(" << stripped_path << "): " << strerror(errno) << std::endl;
       return 1;
    }
    if (chdir(rpms_path)) {
       std::cerr << "create-header-copy: chdir(" << rpms_path << "): " << strerror(errno) << std::endl;
       return 1;
    }

   if ((entry_no = scandir(".", &dirEntries, selectRPMs, alphasort)) < 0)
   {
       std::cerr << "create-header-copy: scandir(" << rpms_path << ",...): " << strerror(errno) << std::endl;
       return 1;
   }

   for (entry_cur = 0; entry_cur < entry_no; entry_cur++) {
       const char *rpm = dirEntries[entry_cur]->d_name;

       int out = openat(stripdir, rpm, O_CREAT|O_EXCL|O_WRONLY, 0644);
       if (out < 0) {
	   if (errno == EEXIST)
	       continue;
	   else {
	       std::cerr << "create-header-copy: " << stripped_path << "/" << rpm << ": cannot create output file" << std::endl;
	       return 1;
	   }
       }
       Header h = readHeader(rpm);
       if (h == NULL) {
	   FD_t infd = Fopen(rpm, "r");
	   h = headerRead(infd, HEADER_MAGIC_YES);
       }
       if (h == NULL) {
	   std::cerr << "create-header-copy: " << rpm << ": cannot read header" << std::endl;
	   return 1;
       }
       FD_t outfd = fdDup(out);
       if (!outfd) {
	   std::cerr << "create-header-copy: error creating file " << v[2] << ": "
	       << strerror(errno) << std::endl;
	   return 1;
       }

       headerWrite(outfd, h, HEADER_MAGIC_YES);
       Fclose(outfd);
       close(out);
   }
   close(stripdir);

   return 0;
}
